<?php
ini_set("display_errors","on");
if(isset($_POST["copy"])){
  $dom = new DOMDocument();
  $dom->loadXML($_POST["copy"]);
  $res=array();
  node2yaml($res, $dom->getElementsByTagName('root')->item(0)->firstChild, '');
  echo implode("\n", $res);
}
elseif(isset($_POST["import"])){
  session_start();
  $dom = new DOMDocument();
  $dom->appendChild($dom->createElement("root"));
  $res = explode("\n", $_POST["import"]);
  yaml2node($res, $dom->firstChild, 0, 0);
  $_SESSION["clipboard"]=$dom->saveXML($dom->firstChild);
  echo $_SESSION["clipboard"];
}
function node2yaml(&$res, $node, $space=''){
	$res[]=$space . $node->nodeName . (!$node->hasChildNodes() ? ':'.json_encode($node->nodeValue) : '');
	$space2 = $space . '  ';
	if($node->hasAttributes()) {
		foreach($node->attributes as $at) {
			$res[]=$space2 . '-' . $at->nodeName . ':' . json_encode($at->nodeValue);
		}
	}
	if($node->hasChildNodes()) {
		foreach($node->childNodes as $ch){
			node2yaml($res, $ch, $space2);
		}
	}
}

function yaml2node($res, $node, $space=0, $i){
/*	@list($nodeName, $nodeValue) = explode(':', trim($res[$i]), 2);
	if($nodeValue) $nodeValue = json_decode($nodeValue);
	if($nodeName=='#text') {
		$n = $node->ownerDocument->createTextNode($nodeValue);
	} else {
		$n = $node->ownerDocument->createElement($nodeName);
	}
	$node->appendChild($n);
	$space2 = $space + 2;
	$i++;*/
	$l = count($res);
	while(true){
		$spaceI = getSpaces($res[$i]);
		if($spaceI>$space){
			$e = substr($res[$i], $spaceI, 1);
			if($e=='-'){
				@list($attrName, $attrValue) = explode(':', substr($res[$i], $spaceI+1), 2);
				$attrValue = json_decode($attrValue);
				$n->setAttribute($attrName, $attrValue);
				$i++;
			} else {
				$i = yaml2node($res, $n, $spaceI, $i);
			}
		} elseif($spaceI==$space) {
			@list($nodeName, $nodeValue) = explode(':', trim($res[$i]), 2);
			if($nodeValue) $nodeValue = json_decode($nodeValue);
			if($nodeName=='#text') {
				$n = $node->ownerDocument->createTextNode($nodeValue);
			} else {
				$n = $node->ownerDocument->createElement($nodeName);
			}
			$node->appendChild($n);
			$i++;
		} else {
			return $i;
		}
		if($i>=$l) break;
	}
	return $i;
}
function getSpaces($txt){
	preg_match('/^\s*/', $txt, $ma);
	return strlen($ma[0]);
}
